package com.iplay.web.notification.storage;

import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.iplay.dto.notification.NotificationDTO;
import com.iplay.service.exception.ResourceNotFoundException;
import com.iplay.service.notification.storage.NotificationStorageService;
import com.iplay.vo.message.MessageReadVO;
import com.iplay.vo.message.MessageVO;
import com.iplay.web.configuration.PaginationConfig;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/api/notifications")
public class NotificationStorageController {

	@Autowired
	private NotificationStorageService notificationService;

	@ApiOperation(notes = "管理員存储消息.read字段为int，0为未读 1为已读 ", value = "")
	@PostMapping
	@PreAuthorize("hasRole('ADMIN')")
	public List<NotificationDTO> saveMessages(
			@Valid @NotNull @ApiParam("Message List.read字段为int，0为未读 1为已读") @RequestBody List<MessageVO> messages) {
		return notificationService.saveMessages(messages);
	}

	@ApiOperation(notes = "分页活得消息。<br>" + "/api/notifications?read=0&page=0&size=5 获得5条最新的未读消息<br>"
			+ "/api/notifications?page=0&size=20 获得20条最新的已读和未读消息（无关状态）<br>"
			+ "/api/notifications?read=1&page=0&size=20 获得20条最新的已读消息<br>", value = "")
	@GetMapping
	@PreAuthorize("hasRole('ADMIN')")
	public Page<NotificationDTO> listMessages(
			@ApiParam("分页参数，可选。例子：page=0&size=5&sort=createdTime,desc。"
					+ "默认情况下size=10, sort=createdTime,desc.") @PageableDefault(value = PaginationConfig.NOTIFICATIONS_PER_PAGE_FOR_ADMIN, sort = {
							"createdTime" }, direction = Sort.Direction.DESC) Pageable pageable,
			@ApiParam("read状态，1为已读 0为未读") @RequestParam(name = "read", required = false) Integer read) {
		Boolean readStatus = integerToBoolean(read);
		return notificationService.listNotifications(readStatus, pageable);
	}

	@ApiOperation(notes = "获得消息数量。<br>" + "/api/notifications/count 获得总的消息数量<br>"
			+ "/api/notifications/count?read=0获得未读消息数量<br>" + "/api/notifications/count?read=1获得已读消息数量<br>", value = "")
	@GetMapping("/count")
	@PreAuthorize("hasRole('ADMIN')")
	public int countMessage(
			@ApiParam("read状态， 0为未读 1为已读") @RequestParam(name = "read", required = false) Integer read) {
		Boolean readStatus = integerToBoolean(read);
		return notificationService.countRead(readStatus);
	}

	@ApiOperation(notes = "修改一条消息状态", value = "")
	@PutMapping("/{id}")
	@PreAuthorize("hasRole('ADMIN')")
	public boolean setRead(@ApiParam("消息id") @PathVariable int id,
			@Valid @ApiParam("包含read状态的实体  0为未读 1为已读") @RequestBody MessageReadVO vo) {
		Boolean readStatus = integerToBoolean(vo.getRead());
		return notificationService.setRead(id, readStatus);
	}

	@ApiOperation(notes = "查看一条消息详情", value = "")
	@GetMapping("/{id}")
	@PreAuthorize("hasRole('ADMIN')")
	public NotificationDTO findById(@ApiParam("消息id") @PathVariable int id) {
		return notificationService.findById(id)
				.orElseThrow(() -> new ResourceNotFoundException("Message with id: " + id + " doesn't exist!"));
	}

	private Boolean integerToBoolean(Integer i) {
		return i == null ? null : (i > 0 ? true : false);
	}

}
